package com.abc.bookstore.application;

import java.io.IOException;
import java.net.ServerSocket;

import com.abc.bookstore.Bookstore;
import com.abc.bookstore.IBookstore;
import com.abc.bookstore.argot.BookLoader;
import com.argot.TypeException;
import com.argot.TypeLibrary;
import com.argot.TypeLibraryLoader;
import com.argot.common.CommonLoader;
import com.argot.dictionary.DictionaryLoader;
import com.argot.meta.MetaLoader;
import com.argot.network.NetArgotLoader;
import com.argot.remote.RemoteLoader;
import com.colony.ColonyEnvironment;
import com.colony.channel.ChannelLoader;
import com.colony.concurrent.SystemThreadPool;
import com.colony.container.zone.RealmContainer;
import com.colony.container.zone.ZoneLoader;
import com.colony.networkvm.NvmLoader;
import com.colony.networkvm.NvmServer;
import com.colony.remote.rpc.RpcLoader;
import com.colony.transport.socket.SocketServer;
import com.colony.zone.CRL;
import com.colony.zone.process.SystemRealm;

public class ServerBookstore
{
	private ColonyEnvironment _server;
	private SocketServer _socketServer;
	
	public ServerBookstore() throws Exception
	{
		// Configure container
		TypeLibrary serverLibrary = configTypeLibrary();
		SystemRealm realm = new SystemRealm("localhost");
		RealmContainer serverContainer = new RealmContainer(realm);
		
		// Configure server
		_server = new ColonyEnvironment(serverContainer,serverLibrary);
		_socketServer = new SocketServer(SystemThreadPool.getThreadPool(),new ServerSocket(500));
		_socketServer.connect();
		_server.addServer("localhost", new NvmServer(new CRL("crl://localhost/hostServer"),_socketServer, null ));
		
		// Add bookstore.
		_server.addObject(new CRL("crl://localhost/bookstore"), IBookstore.TYPENAME, new Bookstore(serverLibrary));		
	}
	
	
	private TypeLibrary configTypeLibrary() 
	throws TypeException, IOException
	{
		TypeLibraryLoader libraryLoaders[] = {
				new MetaLoader(),
				new DictionaryLoader(),
				new CommonLoader(),
				new RemoteLoader(),
				new NetArgotLoader(),
				new RpcLoader(),
				new NvmLoader(),
				new ChannelLoader(),
				new ZoneLoader(),
				new BookLoader()
			};
		
		return new TypeLibrary( libraryLoaders );
	}
	
	public void waitSomeTime() 
	throws InterruptedException
	{
		Thread.sleep(500000);		
	}

	
	public static void main( String[] args )
	{
		try
		{
			ServerBookstore bookstore = new ServerBookstore();
			
			System.out.println( "setup.. waiting for requests");
			bookstore.waitSomeTime();
			System.out.println("closing");
			
		}
		catch (Throwable e)
		{
			e.printStackTrace();
		}
 		
	}
}
